// pages/goods/detail/detail.js
import data from '../../../utils/data.js';
import util from '../../../utils/utils.js';
import User from '../../../utils/user.js';
import Util from "../../../utils/utils";
import {
  GoodsHttp
} from '../../../api/goods.js';
const goodsModel = new GoodsHttp();
let systemInfo = wx.getSystemInfoSync();
let goodsTime = wx.getStorageSync('goodsTime') || 0;
let deltaX = 0; //滑动距离
let stopTouch = false; //滑动权限
let tsa = 'transition: all 0.2s linear;';
Page({
  /**
   * 页面的初始数据
   */
  shareImage:{},
  autoAuth:2,
  channel:{},
  beanCircle:null,
  playTime:0,
  totalTime:goodsTime,
  isFull:false,
  beanAmount:0,
  circleTime:{
    max:5,
    timeIndex:null,
    scrollIndex:null,
  },
  RecommendParam:false,
  RecommendApi:false,
  leftPosition:0,
  data: {
    initUser:true,
    showCircleBox:true,
    userInfo:{},
    channel: {},
    details: [],
    goodsIndex:0,
    aid:0,
    goods_id: 0,
    mall_goods_total: 0,
    windowWidth: systemInfo.windowWidth,
    showBall: false,
    ballY: 0,
    ballX: 0,
    animationY: 0,
    animationX: 0,
    isFollow:false,
    showMore: false,
    showShareDialog:false,
    selectShareImage:0,
    copyText:'',
    shareInfo:false,
    requestShareInfo:false,
    requestCardInfo:false,
    requestShareImg:false,
    showLuckybeanAm:false,
    fontSize:86,
    homePath:'/pages/index/index',
    ts: '',
    translateParam: "", //视图位置
    recommendGoods:{},    //推荐商品
  },
  touch: {
    startX: 0,
    startY: 0,
    time: 0
  },
  /**
   * 页面载入完成
   */
  initPage: function(options){
    let self = this;
    let aid  = 0;
    self.totalTime  = wx.getStorageSync('goodsTime') || 0;
    self.shareImage = new util.HashMap();
    if (options.id) {
      if(options.hasOwnProperty('aid')){
        aid = util.fixInt(options.aid);
      }
      self.setData({
        goods_id: options.id,
        aid:aid
      });
    }else{
      util.msg('商品信息错误!');
      setTimeout(function () {
        wx.navigateBack();
      },1500);
    }
    if(options.hasOwnProperty('recommend')){
      let recommend = decodeURIComponent(options['recommend']);
      recommend     = JSON.parse(recommend);
      if(recommend && recommend.hasOwnProperty('api')){
        self.RecommendApi   = recommend['api'];
        self.RecommendParam = recommend['param'];
      }
    }
    if (options.hasOwnProperty('ekey')) {
      User.UvTrackPut(options.ekey);
    }
    if(self.totalTime > 3000){
      self.totalTime = 0;
    }
    self.setPath();
    self.initData();
  },

  onHide: function () {
    wx.setStorageSync('goodsTime',this.totalTime);
  },
  onUnload: function () {
    wx.setStorageSync('goodsTime',this.totalTime);
    clearTimeout(this.circleTime.scrollIndex);
    clearInterval(this.circleTime.timeIndex);
  },
  closeAction:function(){
    if(this.data.showMore === true){
      this.setData({
        showMore: false,
      })
    }
  },
  onPullDownRefresh: function() {
    if(this.data.initUser === false){
      return false;
    }
    this.initData(true);
  },
  setPath:function(){
    /**
     * 设置首页地址
     */
    let options   = this.options;
    let homePath  = '/pages/home/index/index?v=1';
    let sharePath = '/pages/goods/detail/detail?id=' + this.data.goods_id;
    this.channel  = User.getShareParam(options.hasOwnProperty('uid') ? options['uid'] : 0);
    if(this.channel.shareUid > 0){
      homePath  += '&uid=' + this.channel.shareUid;
      sharePath += '&uid=' + this.channel.shareUid;
    }else{
      sharePath += '&uid=&ekey=';
      this.channel.ekey = '';
    }
    if(this.channel.ekey){
      homePath  += '&ekey=' + this.channel.ekey;
      sharePath += '&ekey=' + this.channel.ekey;
    }
    if(this.data.aid > 0){
      sharePath += '&aid=' + this.data.aid;
    }
    this.shareOption['path'] = sharePath;
    this.setData({
      channel:this.channel,
      homePath:homePath
    });
    util.log('homePath',homePath);
    util.log('shareOption',sharePath);
  },
  initData(ref) {
    let self = this;
    let update = ref || false;
    wx.showNavigationBarLoading();
    /**
     * 拉取基础数据资源
     */
    data.getGoodsDetail({
      goods_id:self.data.goods_id,
      album_id:self.data.aid,
      ekey:this.channel.ekey,
      shop_user_id:self.channel.shareUid,
    }, function(result) {
      util.log('goodsDetails', result);
      if(result === false){
        util.msg('商品信息错误!');
        setTimeout(function () {
          wx.navigateBack();
        },1500);
      }else{
        /**
         * 格式化优惠券时间范围
         */
        result = self.formatDetail(result);
        self.setData({
          details: [result],
        });

        data.getMailGoods(result.mall_id,result.platform_type,function (result) {
          self.setData({
            mall_goods_total:result.total
          });
        }, 1, true);

        util.request({
          url:'/wxgroup/WxGoodsPoster',
          data:{
            "goods_id":self.data.goods_id,
          },
          loading:2,
          handle:true,
          callback:function (result) {
            self.shareOption['imageUrl'] = result['res'];
          }
        });

        self.setGoodsParam(0);
        self.initCircle();
        /**
         * 加载下一页商品
         */
        if(self.RecommendApi !== false){
          util.request({
            url:self.RecommendApi,
            data:self.RecommendParam,
            loading:2,
            callback:function (result) {
              let flag = false;
              let lastIndex = result['res']['goods_list'].length - 1;
              for(let i=0;i<result['res']['goods_list'].length;i++){
                if(result['res']['goods_list'][i]['goods_id'] === self.data.goods_id){
                  flag = true;
                  if(i === lastIndex){
                    self.watchGoodsId();
                  }
                  continue;
                }
                if(flag === false){
                  continue;
                }
                data.getGoodsDetail({
                  goods_id:result['res']['goods_list'][i]['goods_id'],
                  album_id:self.data.aid,
                  ekey:self.channel.ekey,
                  shop_user_id:self.channel.shareUid,
                }, function(result) {
                  let details = self.data.details;
                  details.push(self.formatDetail(result));
                  self.setData({
                    details:details
                  });
                },false,2);
              }
            }
          })
        }else{
          //获取相似推荐数据
          goodsModel.GetRecommend({
            goods_id: self.data.goods_id
          }).then((res) => {
            let set = self.data.details[0];
            set['recommed'] = res.goods_list;
            let d = {};
            d['details[0]'] = set;
            self.setData(d);
          });
        }
      }
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, update);
  },
  /**
   * 预处理商品详情
   * @param result
   * @returns {*}
   */
  formatDetail:function(result){
    console.log('formatDetail result', result);
    if(result.coupon_number > 0){
      result.coupon_start_time = util.formatTime('yyyy-MM-dd',result.coupon_start_time);
      result.coupon_end_time   = util.formatTime('yyyy-MM-dd',result.coupon_end_time);
    }
    result['mall_logo'] = util.getMallLogoText(result['mall_name']);
    result.fontSize = 86;
    if(result.coupon_discount.length > 3){
      result.fontSize = 76;
    }
    if(result.coupon_discount.length > 4){
      result.fontSize = 66;
    }
    console.log('formatDetail isFollow', result.is_collection)
    result.isFollow = parseInt(result.is_collection) === 1;
    return result;
  },
  onTouchstart: function (e) {
    let touch = e.touches[0];
    this.touch.startX = touch.pageX;
    this.touch.startY = touch.pageY;
    this.touch.time = new Date().getTime();
    this.leftPosition = this.data.goodsIndex * this.data.windowWidth;
    this.setData({
      ts: '',
    });
  },
  onTouchmove: function (e) {
    let touch = e.touches[0];
    let index = this.data.goodsIndex;
    let offsetX = 0;
    deltaX = touch.pageX - this.touch.startX;
    let deltaY = touch.pageY - this.touch.startY;
    let absX = Math.abs(deltaX);
    let absY = Math.abs(deltaY);
    let self = this;

    if(this.data.showMore === true){
      this.setData({
        showMore: false,
      });
    }
    clearTimeout(this.circleTime.scrollIndex);
    this.circleTime.scrollIndex = setTimeout(function () {
      self.circleTime.max = 5;
    },500);
    if(this.circleTime.max <= 1) {
      this.circleTime.max += 1;
    }

    if(absY > 15 && absX < absY){
      return false;
    }

    if(absX < 5){
      return false;
    }

    if (deltaX < 0) {
      offsetX = this.leftPosition + absX;
      this.setData({
        translateParam: `translate(-${offsetX}px,0%)`
      });
    } else {
      if (index > 0) {
        offsetX = this.leftPosition - absX;
        this.setData({
          translateParam: `translate(-${offsetX}px,0%)`
        });
      }
    }
  },
  onTouchend: function (e) {
    // 阻止连续滑动
    let startTime = this.touch.time; //start时间
    let endTime = new Date().getTime(); //end时间
    let list = this.data.details; //数组
    let goodsIndex = this.data.goodsIndex; //索引
    if (stopTouch) {
      this.setData({
        ts: tsa,
        translateParam: `translate(-${goodsIndex * 100}%,0%)`
      });
      return;
    }

    //时间超过3秒滑动无效 这里暂时不操作
    if ((endTime - startTime) > 3000) {

    }
    // 不能连续滑动 必须等待滑动完成动画过渡
    if (deltaX > 50 || deltaX < -50) {
      this.stopTouchFunc();
    }
    // 滑动距离不够
    if (deltaX < 50 && deltaX > -50) {
      this.setData({
        ts: tsa,
        translateParam: `translate(-${goodsIndex * 100}%,0%)`
      });
      return
    }
    // 滑动超过30执行 下滑
    if (deltaX > 50) {
      // 到第一个的时候不能在继续滑动了
      if ((goodsIndex === 0)) {
        this.initData();
        Util.log('到顶了，刷新数据');
        return
      }
      goodsIndex -= 1;
      this.tabHome(goodsIndex);
    }
    // 滑动小于-30执行 上滑
    if (deltaX < -50) {
      // 到第一个的时候不能在继续滑动了 或者需要加载数据
      if ((goodsIndex === list.length - 1)) {
        Util.log('到底了 不能在往下了');
        return
      }
      goodsIndex += 1;
      this.tabHome(goodsIndex)
    }
    //初始化配置参数
    deltaX = 0;
    this.touch.time = 0;
    setTimeout(() => {
      // 先执行动画 在切换 提升流畅性
      this.setIndex(goodsIndex);
      this.watchGoodsId()
    }, 310);
    clearTimeout(this.circleTime.scrollIndex);
  },
  watchGoodsId: function () {
    let self = this;
    let list = this.data.details;
    let goodsIndex = this.data.goodsIndex;
    let lastIndex = list.length - 1;
    let item = {};
    if (this.data.details.hasOwnProperty(goodsIndex)) {
      item = this.data.details[goodsIndex];
    } else {
      return false;
    }
    // 当滑动到最后一个的时候 加载列表
    if (lastIndex === goodsIndex) {
      Util.log('最后一个了。');
      if(self.RecommendApi !== false){
        if(self.RecommendParam.hasOwnProperty('page')){
          self.RecommendParam['page'] ++;
        }
        util.request({
          url:self.RecommendApi,
          data:self.RecommendParam,
          loading:2,
          callback:function (result) {
            for(let i=0;i<result['res']['goods_list'].length;i++){
              data.getGoodsDetail({
                goods_id:result['res']['goods_list'][i]['goods_id'],
                album_id:self.data.aid,
                ekey:self.channel.ekey,
                shop_user_id:self.channel.shareUid,
              }, function(result) {
                let details = self.data.details;
                details.push(self.formatDetail(result));
                self.setData({
                  details:details
                });
              },false,2);
            }
          }
        })
      } else {
        Util.msg('已经到底了，刷新试试吧！');
      }
    }
    this.setGoodsParam(goodsIndex)
  },
  // 设置当前播放的
  setGoodsParam: function (i) {
    let result = {};
    let self = this;
    if (this.data.details.hasOwnProperty(i)) {
      result = this.data.details[i];
    } else {
      return false;
    }
    self.shareOption['title']    = "【"+(result.platform_type === 3 ? '京东' : '拼多多')+"】优惠券"+result['coupon_discount']+"元， 原价"+result['money']+"元，券后" + result['price'] + '元';
    self.shareOption['imageUrl'] = result.images[0];
    self.setData({
      detail:result
    });
    if(!result.hasOwnProperty('recommend')){
      goodsModel.GetRecommend({
        goods_id: result.goods_id
      }).then((res) => {
        let set = {};
        result['recommend'] = res.goods_list;
        set['details['+i+']'] = result;
        self.setData(set);
      });
    }
    wx.setNavigationBarTitle({
      title: result.title
    });
  },
  tabHome: function (i) {
    let top = -(i) * 100;
    this.setData({
      ts: tsa,
      translateParam: `translate(${top}%,0%)`
    });
  },
  setIndex: function (i) {
    this.setData({
      goodsIndex: i
    })
  },
  stopTouchFunc: function () {
    // 锁定滑动权限
    stopTouch = true;
    // 动画是0.4s 预估有一点dom渲染时间 0.2s 就延迟0.7s 时间在准滑动哈
    setTimeout(() => {
      stopTouch = false
    }, 400)
  },
  moreMenus: function(){
    let self = this;
    self.setData({
      showMore: !self.data.showMore,
    })
  },
  /**
   * 领取卡券
   */
  receiveCard:function(){
    //判断优惠券剩余数量
    let self = this;
    console.log(self.data.detail);
    if (self.data.detail.unsale) {
      return;
    }
    console.log(self.data.detail);
    if(util.fixInt(self.data.detail.platform_type) === 2){
      util.msg('淘宝商品不支持小程序展示，请下载APP体验');
      return;
    }
    self.setData({
      requestCardInfo:true,
    });
    self.getUserInfo(function (result) {
      self.setPath();
      let channel = User.getShareParam(0);
      util.request({
        url: util.api.GetShearShortUrl,
        data: {
          goods_id:self.data.goods_id,
          shareId:channel.shareUid,
          aid:self.data.aid,
          userId:result.uid,
          ekey:channel.ekey,
        },
        error:function(){
          self.setData({
            requestCardInfo:false,
          });
        },
        callback: function (result) {
          self.setData({
            requestCardInfo:false,
          });
          if(result['data']){
            util.log('开始跳转！',result['data']);
            wx.navigateToMiniProgram({
              appId: result['data']['app_id'],
              path: result['data']['page_path'],
              success:function (res) {
                util.log('跳转成功');
              },
              fail:function (res) {
                util.log('跳转失败！',res);
              },
              complete:function (res) {
                util.log('跳转完成！',res);
              }
            });
          }else{
            util.msg('优惠券信息获取失败!');
          }
        }
      });
    },function () {
      self.setData({
        requestCardInfo:false,
        initUser:false
      });
    });
  },
  /**
   * 打开分享弹窗
   */
  openShare:function () {
    let self = this;
    if (self.data.detail.unsale) {
      return;
    }
    if(util.fixInt(self.data.detail.platform_type) === 2){
      util.msg('由于小程序不支持淘宝商品，请下载或打开巷友app体验');
      return;
    }
    self.getUserInfo(function (result) {
      self.setPath();
      let channel = User.getShareParam(0);
      if(!self.data.shareInfo){
        self.setData({
          requestShareInfo:true,
        });
        util.request({
          url:util.api.PreShare,
          data:{
            shareId:channel.shareUid,
            aid:self.data.aid,
            userId:0,
            goods_id:self.data.goods_id
          },
          handle:true,
          callback:function (result) {
            let _copyText = [];
            let _data = result.res;
            _copyText.push(_data.GoodsName);
            _copyText.push('-------------------------------');
            _copyText.push('拼团价：¥'+_data.MinNormalPrice);
            _copyText.push('券后内部价：¥'+_data.PostPrice);
            _copyText.push('已售出：'+_data.SalesTip);
            _copyText.push('-------------------------------');
            _copyText.push('【购买方式】');
            _copyText.push('点击领券链接购买：' + _data.ShortUrl);
            self.setData({
              requestShareInfo:false,
              shareInfo:_data,
              copyText:_copyText.join("\n"),
              showShareDialog:true
            });
            /**
             * 自动生成一张图
             */
            self.switchShareImage({
              currentTarget:{
                dataset:{
                  index:0
                }
              }
            });
            if(!self.shareOption['imageUrl']){
              self.shareOption['imageUrl'] = _data.GoodsImageURL[0];
            }
          },error:function (result) {
            self.setData({
              requestShareInfo: false
            });
          }
        });
      }else{
        self.setData({
          showShareDialog:true
        });
      }
    },function () {
      self.setData({
        initUser:false
      });
    });
  },
  /**
   * 复制分享文字并下载图片
   * @param e
   */
  copyShareInfo:function (e) {
    let self = this;
    let type = e.currentTarget.dataset.type;
    let key  = '';
    wx.setClipboardData({
      data: this.data.copyText
    });
    self.setData({
      isCopy:true,
    });
    if(type === '1' || type === '2'){
      key = type === '1' ? 'wx_url' : 'h5_url';
      self.getShareImage(self.data.selectShareImage,function (urls) {
        wx.previewImage({
          urls:[
            urls[key],
          ]
        });
      });
    }
  },
  /**
   * 收藏到线上
   */
  collection: function(){
    let self = this;
    console.log(self);
    self.getUserInfo(function (result) {
      self.setPath();
      if(self.data.detail.isFollow === true){
        util.request({
          url:util.api.delFollow,
          data:{
            good_ids:[
              self.data.goods_id
            ]
          },
          loading:1,
          callback:function (res) {
            util.msg('取消收藏');
            self.setData({
              'detail.isFollow':false,
            });
          }
        });
      }else{
        util.request({
          url:util.api.addFollow,
          data:{
            good_id:self.data.goods_id
          },
          loading:1,
          callback:function (res) {
            util.msg('收藏成功');
            self.setData({
              'detail.isFollow':true,
            });
          }
        });
      }
    },function () {
      self.setData({
        initUser:false
      });
    });
  },
  closeShareDialog:function(){
    this.setData({
        showShareDialog:false
    });
  },
  switchShareImage:function(e){
    let self  = this;
    let index = e.currentTarget.dataset.index;
    self.setData({
        selectShareImage:index
    });
    self.shareOption['imageUrl'] = this.data.shareInfo.GoodsImageURL[index];
    /**
     * 主动拉取合成的海报图片
     */
    self.getShareImage(index);
  },
  /**
   * 下载图片到本地相册
   * @param url
   */
  downImageToLocal:function (url) {
    wx.downloadFile({
      url: url,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (res) {
            util.msg('图片已保存到您的手机相册!')
          },
          fail: function (err) {
            util.msg('保存到相册失败:' + err.errMsg);
          }
        })
      }
    });
  },

  /**
   * 获取合成的分享图片
   * @param index
   * @param callback
   */
  getShareImage:function (index,callback) {
    let self = this;
    let key  = index;
    let urls = self.shareImage.get(key);
    if(urls){
      callback && callback(urls);
    }else{
      self.setData({
        requestShareImg:true,
      });
      let channel = User.getShareParam(0);
      let param = {
        url_type:1,
        goods_url:self.data.shareInfo.GoodsImageURL[index],
        goods_id:self.data.goods_id,
        aid:self.data.aid,
      };
      if(channel.shareUid > 0){
        param['ownerUserId'] = channel.shareUid;
      }
      data.QrcodeUrlShera(param,function (result) {
        self.setData({
          requestShareImg:false,
        });
        if(result.status === 'ok'){
          self.shareImage.put(key,result.res);
          callback && callback(result.res);
        }else{
          util.msg(result.msg);
        }
      });
    }
  },
  onClosePopup:function (e) {
    let type = e.currentTarget.dataset.type;
    if(type === 'ServiceText'){
      this.setData({
        showServiceText:false
      });
    }
    if(type === 'ShareDialog'){
      this.setData({
        showShareDialog:false
      });
    }
  },

  initCircle:function(){
    let self = this;
    /*进度条 */
    // 获得circle组件
    self.beanCircle = self.selectComponent("#bean_circle");
    self.beanCircle.init();
    util.request({
      url:"s/yddgoods/GoodsGetBean",
      autoAuth: 2,
      loading: 2,
      data:{
        goods_id: self.data.goods_id,
      },
      handle:true,
      callback:function (result) {
        if(result.status === 'ok'){
          if(result.res.status === 1){
            self.beanCircle.inc(self.totalTime);
            self.circleTime.timeIndex = setInterval(function () {
              if(self.circleTime.max > 0){
                self.circleTime.max --;
                self.totalTime += 100;
                self.beanCircle.inc(self.totalTime);
              }
            },1000);
          }else{
            self.beanCircle.setFull();
          }
        }
      }
    });
  },
  stepCircle:function(e){
    this.totalTime = e.detail;
    if(this.totalTime > 30){
      this.totalTime = 0;
    }
  },
  fullBeanCircle:function () {
    let self = this;
    this.isFull = true;
    this.totalTime = 0;
    clearInterval(self.circleTime.timeIndex);
    Util.request({
      url: '/s/yddgoods/GoodsGetBeanStatus',
      autoAuth: 2,
      loading: 2,
      data: {
        goods_id: this.data.goods_id,
      },
      handle:true,
      callback:function (result) {
        if(result.status === 'ok'){
          let setData = {};
          setData['showLuckybeanAm'] = true;
          setData['LuckybeanAmount'] = result.res.bean_num;
          self.setData(setData);
          setTimeout(function() {
            self.setData({
              showLuckybeanAm: false
            });
          }, 2000);
        }
      }
    });
  },
  tapToPage:function (e) {
    this.toPage(e.detail);
  },
  showTipBox:function (e) {
    let type = parseInt(e.detail.type);
    let self = this;
    let param = {
      loading:true,
    };
    let tipData = {};
    let app = getApp();
    if(type === 1){
      param.isJava = true;
      param.url = '/bonus/freeOrder/list';
      tipData = {
        title:'这些人正在参与免单',
        btn:'查看如何免单',
        url:'',
        type:1,
        data:[]
      };
      if(app.globalData.pageConfig.freeSheet){
        tipData.url = app.globalData.pageConfig.freeSheet.path
      }
    }
    if(type === 2){
      param.url = 'luckdraw/UserMakeMoneyPopup';
      param.data = {
        popup:1,
      };
      tipData = {
        title:'这些人正在省钱',
        btn:'查看如何省钱',
        url:'',
        type:2,
        data:[]
      };
      if(app.globalData.pageConfig.coursePage){
        tipData.url = app.globalData.pageConfig.coursePage.path
      }
    }
    if(type === 3){
      param.url = 'luckdraw/UserMakeMoneyPopup';
      param.data = {
        popup:2,
      };
      tipData = {
        title:'这些人正在参与赚钱',
        btn:'查看如何赚钱',
        url:'',
        type:3,
        data:[]
      };
      if(app.globalData.pageConfig.upgradeHousekeeper){
        tipData.url = app.globalData.pageConfig.upgradeHousekeeper.path
      }
    }
    param.callback = function (result) {
      console.log(result);
      let data = [];
      let item = {};
      if(type === 2 || type ===3){
        for(let i = 0;i<result.res.usermoney.length;i++){
          item = result.res.usermoney[i];
          data.push({
            avatar:item['avatar'],
            nickname:item['nickName'],
            money:'￥' + util.formatMoney(item['money']),
            text:type === 2 ? '刚刚领取了优惠券节省' : '刚刚分享商品赚了',
          });
        }
      }
      if(type === 1){
        for(let i = 0;i<result.res.list.length;i++){
          item = result.res.list[i];
          data.push({
            avatar:item['avatar'],
            nickname:item['nickName'],
            money:'',
            text:'正在参与免单',
          });
        }
      }

      tipData['data'] = data;
      self.setData({
        tipData:tipData,
        showTipText:true
      });
    };
    util.request(param);
  },
  onCloseTipPopup:function(){
    this.setData({
      showTipText:false,
    })
  },
});
